package com.cloud.code.sax.dom4j;

import com.cloud.code.sax.Book;
import com.thoughtworks.xstream.XStream;
import lombok.SneakyThrows;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;

public class Test {

    @SneakyThrows
    public static void main(String[] args) {

        Book book = new Book();
        book.setName("百科全书");
        book.setAuthor("xialiu");

        //生成xml
        XStream xStream = new XStream();
        xStream.toXML(book);

        //解析xml
        dom4j();

    }

    private static void dom4j() throws DocumentException {
        SAXReader saxReader = new SAXReader();
        InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("com/cloud/code/sax/boot.xml");
        Document document = saxReader.read(resourceAsStream);

        Element rootElement = document.getRootElement();
        Iterator<Element> elementIterator = rootElement.elementIterator();

        ArrayList<Book> books = new ArrayList<>();
        while (elementIterator.hasNext()){
            Book book = new Book();
            Element next = elementIterator.next();
            Iterator<Element> chard = next.elementIterator();
            while (chard.hasNext()){
                Element boot = chard.next();
                String name = boot.getName();
                String text = boot.getText();
                System.out.println(name+" "+text);
            }
        }
    }
}
